package com.online.findagentserver.controller;

import com.alibaba.fastjson.JSON;
import com.online.findagentserver.domain.SSId;
import com.online.findagentserver.domain.SessionObj;
import com.online.findagentserver.service.FindAgentService;
import com.online.findagentserver.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Author: liuqing
 * @Despriction:
 * @Date:Created in 2018/4/28 11:47
 * @Modify By:
 */
@RestController
public class FindAgentController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private FindAgentService findAgentService;


    @Value("${com.session.max}")
    private int sessionMax;

    @PostMapping("/closeChatSession")
    public Map closeChatSession(@RequestBody Map map) {
        Integer service_id = (Integer) map.get("service_id");
        Integer eId = (Integer) map.get("e_id");
        List<SessionObj> sessionObjs = (List<SessionObj>) map.get("session_objs");
        Map restMap = new HashMap(16);
        if (sessionObjs == null || sessionObjs.size() == 0) {
            restMap.put("result", 0);
            return restMap;
        }
        SessionObj sessionObj;
        String[] keysOfOpenId = new String[sessionObjs.size()];
        Collection<String> collection = new ArrayList<>();
        for (int i = 0; i < sessionObjs.size(); i++) {
            sessionObj = sessionObjs.get(i);
            keysOfOpenId[i] = sessionObj.getOpenId();
            collection.add(sessionObj.getSessionId() + "");
        }

        redisService.deleteMessage(collection);
        redisService.deleteChatSession(service_id + "", keysOfOpenId);
        findAgentService.endTime(sessionObjs, eId);

        restMap.put("result", 0);
        return restMap;
    }

    @PostMapping("/findWaitUser")
    public Map findWaitUser(@RequestBody Map map) {
        System.out.println("进来了。。。");
        Integer serviceId = (Integer) map.get("service_id");
        Integer eId = (Integer) map.get("e_id");
        Map restMap = new HashMap(16);
        if (StringUtils.isEmpty(serviceId) || StringUtils.isEmpty(eId)) {
            return null;
        }
        Set<Object> keys = redisService.getWaitCompanyOpenId(eId + "");
        if (keys != null && keys.size() != 0) {
            String restKey = "";
            for (Object key : keys) {
                restKey = (String) key;
                break;
            }
            String sessionId = redisService.getWaitCompanyOpenId(eId + "", restKey);
            restMap.put("result", "1");
            restMap.put("session_id", sessionId);
            restMap.put("open_id", restKey);
            SSId ssId = new SSId(Integer.parseInt(sessionId), serviceId);
            String ssIdStr = JSON.toJSONString(ssId);
            redisService.saveCompanyOpenId(eId + "", restKey, ssIdStr);

            redisService.removeWaitCompanyOpenId(eId + "", restKey);
            return map;
        } else {
            restMap.put("result", "0");
            return restMap;
        }
    }

    @PostMapping("/findAgentServer")
    public Map findAgentServer(@RequestBody Map map) {
        System.out.println("又进来了。。。。。。。。。。。");
        Object openId = map.get("open_id");
        Integer eId = (Integer) map.get("e_id");
        Map restMap = new HashMap(16);

        if (StringUtils.isEmpty(openId)) {
            System.out.println("openId is null....");
            return null;
        }
        restMap.put("open_id", openId);

        String wait = redisService.findWaitSessionAgent(eId+"",(String) openId);
        if (wait!=null){
            System.out.println("wait!=null.......");
            restMap.put("session_id", Integer.parseInt(wait));
            restMap.put("service_id", -1);
            return restMap;
        }

        String str = redisService.findSessionAgent(eId + "", (String) openId);
        if (!StringUtils.isEmpty(str)) {
            SSId ssId = JSON.parseObject(str, SSId.class);
            restMap.put("session_id", ssId.getSession_id());
            restMap.put("service_id", ssId.getService_id());
        } else {
            int restServiceId;
            int aId = findAgentService.getAId(eId, (String) openId);
            if (aId == -1) {
                restServiceId = shuffleAId(eId + "");
            } else {
                if (redisService.getSessionCount(aId + "") < sessionMax) {
                    restServiceId = aId;
                } else {
                    restServiceId = shuffleAId(eId + "");
                }
            }

            int respSessionId = findAgentService.getSessionId((Integer) eId, (String) openId);
            if (restServiceId == -1) {
                redisService.saveWaitCompanyOpenId(eId + "", (String) openId, respSessionId + "");
            } else {
                findAgentService.saveSsc(restServiceId,respSessionId,eId);

                SSId ssId = new SSId(respSessionId, restServiceId);
                //保存到redis 缓存3 和缓存4
                String ssIdStr = JSON.toJSONString(ssId);
                redisService.saveCompanyOpenId(eId + "", (String) openId, ssIdStr);
                redisService.saveSessionOfAgentOpenId(restServiceId + "", openId + "", respSessionId + "");
            }

            restMap.put("session_id", respSessionId);
            restMap.put("service_id", restServiceId);
        }

        System.out.println("restMap:serivce_id:"+restMap.get("service_id"));
        System.out.println("restMap:session_id:"+restMap.get("session_id"));
        return restMap;
    }

    private int shuffleAId(String eId) {
        Set<String> set = redisService.findAIds(eId);
        List<String> aIds = new ArrayList<>(set);

        if (aIds != null) {
            Collections.shuffle(aIds);
            for (int i = 0; i < aIds.size(); i++) {
                if (redisService.getSessionCount(aIds.get(i)) < sessionMax) {
                    return Integer.parseInt(aIds.get(i));
                }
            }
        }
        return -1;
    }
}
